package com.green.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeUtil {

	private static final int ONE_DAY_TIME = 24 * 60 * 60 * 1000;
	private static final String DATE_FORMAT = "yyyy-MM-dd";
	private static final String DATETIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
	private static final String MONTH_FORMAT = "yyyy-MM";
	private static final String MINUTE_FORMAT = "yyyy-MM-dd HH:mm";

	public static Date transStringToDate(String date) {
		try {
			if (date.length() == 10) {
				SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
				return format.parse(date);
			} else {
				SimpleDateFormat timeFormat = new SimpleDateFormat(DATETIME_FORMAT);
				return timeFormat.parse(date);
			}
		} catch (ParseException e) {
			return null;
		}
	}

	public static String transDateToTimeStr(Date date) {
		SimpleDateFormat timeFormat = new SimpleDateFormat(DATETIME_FORMAT);
		return timeFormat.format(date);
	}

	public static String transDateToString(Date date) {
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
		return format.format(date);
	}

	public static String transStringToDateStr(String str) {
		try {
			return str.substring(0, 10);
		} catch (Exception e) {
			return "";
		}
	}

	public static String transMonthToStr(Date date) {
		SimpleDateFormat monthFormat = new SimpleDateFormat(MONTH_FORMAT);
		return monthFormat.format(date);
	}

	public static String transStringToMinuteStr(String str) {
		if (str != null && str.length() > 16) {
			try {
				return str.substring(0, 16);
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		return "";
	}

	public static String transStringToMinuteStr(Date date) {
		if (date != null) {
			try {
				SimpleDateFormat minuteFormat = new SimpleDateFormat(MINUTE_FORMAT);
				return minuteFormat.format(date);
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		return "";
	}
	
	public static int getRemainingDays(Date date){
		long endTime = date.getTime();
		long startTime = System.currentTimeMillis();
		return (int) ((endTime - startTime) / ONE_DAY_TIME) + 1;
	}
	public static int getSubtractDay(Date date){
		long endTime = date.getTime();
		long startTime = System.currentTimeMillis();
		return (int) ((endTime - startTime) / ONE_DAY_TIME);
	}
	public static long minusDates(Date date1,Date date2){
		
		return date1.getTime()-date2.getTime();
	}
	public static Date getMaxDate(Date date1,Date date2){
		long d1 = 0;
		long d2 = 0;
		if(date1!=null) d1 = date1.getTime();
		if(date2!=null) d2 = date2.getTime();
		long result = d2-d1;
		if(result==0) 
			return new Date();
		else if(result>0)
			return date2;
		else
			return date1;
	}
}
